const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const { exec } = require('child_process');

let ffmpegProcess; // 用于存储 FFmpeg 进程

function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            enableRemoteModule: true,
        },
    });

    win.loadURL('http://localhost:8080');
}

function startRTSPStream() {
    alert('开始推流');

    const ffmpegCommand = process.platform === 'win32'
        ? 'ffmpeg -loglevel debug -f gdigrab -framerate 30 -i desktop -vcodec libx264 -bsf:v h264_mp4toannexb -acodec aac -f rtsp -rtsp_transport tcp rtsp://192.168.1.112:554/live/202401111410?sign=e8ca4a025af9c40bcad32498edf4b097'
        : process.platform === 'darwin'
            ? 'ffmpeg -loglevel debug -f avfoundation -framerate 30 -i "0" -vcodec libx264 -bsf:v h264_mp4toannexb -acodec aac -f rtsp -rtsp_transport tcp rtsp://192.168.1.112:554/live/202401111410?sign=e8ca4a025af9c40bcad32498edf4b097'
            : 'ffmpeg -loglevel debug -f x11grab -video_size 1920x1080 -i :0.0 -vcodec libx264 -bsf:v h264_mp4toannexb -acodec aac -f rtsp -rtsp_transport tcp rtsp://192.168.1.112:554/live/202401111410?sign=e8ca4a025af9c40bcad32498edf4b097';

    ffmpegProcess = exec(ffmpegCommand, (error, stdout, stderr) => {
        if (error) {
            console.error(`启动推流失败: ${error.message}`);
            return;
        }
        if (stderr) {
            console.error(`FFmpeg 错误: ${stderr}`);
            return;
        }
        console.log(`FFmpeg 输出: ${stdout}`);
    });
}

function stopRTSPStream() {
    if (ffmpegProcess) {
        ffmpegProcess.kill('SIGINT'); // 发送 SIGINT 信号以优雅地停止进程
        ffmpegProcess = null; // 清空进程引用
        console.log('推流已停止');
    }
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

ipcMain.on('start-stream', () => {
    console.log('接收到开始推流的请求');
    startRTSPStream();
});

ipcMain.on('stop-stream', () => {
    console.log('接收到结束推流的请求');
    stopRTSPStream();
});
